#include <thread>
#include <vector>
#include <iostream>
#include <fstream>
#include "log/log.h"
#include "clocker/clocker.h"
#include "./smart/smart_mpp_encoder.hpp"
#include "../camera/smart/smart_camera.hpp"

int main(const int argc, const char* argv[])
{
    int ret;
    std::vector<uint8_t> data;
    enc_para_t enc_para{0};
    SmartCamera cam;
    cam.init("/dev/video0", 5, 1920, 1080, V4L2_PIX_FMT_UYVY);

    // 编码器参数配置
    enc_para.width = 1920;
    enc_para.height = 1080;
    enc_para.rc_mode = MPP_ENC_RC_MODE_VBR;
    enc_para.fmt = MPP_FMT_YUV422_UYVY;
    enc_para.type = MPP_VIDEO_CodingAVC;
    SmartMppEncoder encoder(enc_para);

    // 获取编码头文件信息写入文件
    std::ofstream file("test.h264", std::ios::out | std::ios::binary); // 打开文件用于读取
    ret = encoder.get_enc_header(data);
    if (ret > 0 && data.size() > 0) {
        file.write(reinterpret_cast<const char*>(data.data()), data.size());
        log_debug("write h264 header data.size():%d.", data.size());
    }

    log_debug("start recv camera frame.");
    getchar();
    cam.loop_recv_frame([&cam, &encoder, &file](uint8_t *buf, uint32_t len){
        static int count;
        std::vector<uint8_t> put_data(buf, buf+len);
        log_debug("put_data addr:%p, len:%d.", put_data.data(), put_data.size());

        static std::vector<uint8_t> get_data;

        clocker_begin();
        encoder.sync_encode(buf, len, get_data);
        file.write(reinterpret_cast<const char*>(get_data.data()), get_data.size());
        clocker_end();

        // // 打印前10个字符
        // for (int i = 0; i < 10; ++i) {
        //     if (i >= get_data.size()) break;
        //     printf("%2x ", get_data.data()[i]);
        // }

        // 停止条件
        if (++count >= 100) {
            cam.stop();
        }
    });

    file.close();
    return 0;
}
